﻿using CommonLib.Attr;
using CommonLib.Base;
using CommonLib.CodeEntity;
using CommonLib.Util;
using System.Text.RegularExpressions;

namespace Oracle.Lexer;

[Order(4)]
public class ExecLexer : BaseLexer
{

    public override bool Check()
        => Regex.IsMatch(Txt, "^[A-Z_][A-Z0-9._]+\\s*\\(") && (Real.EndsWith(")")|| Real.EndsWith(");"));

    protected override BaseCodeEntity Run()
    {
        var name = Txt[..Txt.IndexOf("(")].Trim();
        var kind = string.Empty;
        if (OracleConst.SysFunction.Any(f => f.EqualsIgnoreCase(name))) kind = "Sys";
        var entity = new ExecCodeEntity(name, kind);
        var pras = Regex.Match(Txt, "\\((.*)\\)").Result("$1");
        var list = pras.TrimSplit(',').Select(s => s.Trim())
            .Where(s => !string.IsNullOrEmpty(s)).ToList();
        for (int i = 0; i < list.Count; i++)
        {
            var item = list[i];
            while (!item.IsFull())
            {
                var next = list[++i];
                item = string.Format("{0},{1}", item, next);
            }
            entity.Params.Add(SqlFactory.Create(item).Execute());
        }
        return entity;
    }
}
